/**
 * <b>项目名：</b>meizuapi<br/>
 * <b>包名：</b>com.meizu.api.meizuapi<br/>
 * <b>文件名：</b>Monitor.java<br/>
 * <b>版本信息：</b> @version 1.0.0<br/>
 * <b>日期：</b>2013-5-4-下午4:02:16<br/>
 * <b>Copyright (c)</b> 2013魅族公司-版权所有<br/>
 *
 */

package org.apitool.main;

import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Types;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import org.mozilla.javascript.Context;
import org.mozilla.javascript.ScriptableObject;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import com.alibaba.fastjson.JSONObject;
import com.mysql.jdbc.Connection;

/**
 * <b>类名称：</b>Monitor<br/>
 * <b>类描述：</b>
 * 
 * <pre>
 </pre>
 * 
 * <br/>
 * <b>创建人：</b>张军强<br/>
 * <b>修改人：</b>张军强<br/>
 * <b>修改时间：</b>2013-5-4 下午4:02:16<br/>
 * <b>修改备注：</b><br/>
 * 
 * @version 1.0.0<br/>
 */

// public class Monitor {
//
// }

public class Monitor implements Job {

	private static Connection con = null;
	// private static PreparedStatement stmt = null;

	static {

		Properties info = new Properties();
		try {

			String url = "jdbc:mysql://127.0.0.1/%s?" + "user=%s&password=%s";

			Map<String, String> urlMap = JSONObject.parseObject(Main.jdbc, Map.class);

			con = (Connection) DriverManager.getConnection(String.format(url, urlMap.get("db"), urlMap.get("user"), urlMap.get("pwd")));
			// con = (Connection)
			// DriverManager.getConnection("jdbc:mysql://127.0.0.1/monitor?" +
			// "user=root&password=root");
			// String sql =
			// "INSERT INTO monitor ( host, url, param, result,create_time) VALUES ( ?, ?, ?, ?,? )";

			// stmt.execute("INSERT INTO monitor.monitor ( host, url, param, result) VALUES ( 'host', 'url', 'param', 'result')");
			// stmt.execute(sql)
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	public static void main(String[] args) {

	}

	/**
	 * 创建一个新的实例 Monitor.
	 */

	public Monitor() {
		// TODO Auto-generated constructor stub
	}

	private static String safeStr(String str) {

		return str.replaceAll("\'", "\\\\'");
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.quartz.Job#execute(org.quartz.JobExecutionContext)
	 */

	@Override
	public void execute(JobExecutionContext context) throws JobExecutionException {

		ScriptableObject scope = null;
		try {
			String projectPath = Main.getProjectPath();
			String filename = projectPath + "/conf/assert.js";
			if (!Main.conf.equals("")) {
				filename = Main.conf + "/conf/assert.js";
			}
			String assertjs = Main.getFile(filename);
			Context cx = org.mozilla.javascript.Context.enter();
			scope = cx.initStandardObjects();
			cx.evaluateString(scope, assertjs, "assert.js", 1, null);
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("assert.js出错");
			return;
		}

		// System.out.println("**********************************************");
		HashMap<String, String> api = (HashMap) context.getJobDetail().getJobDataMap().get("api");
		String host = api.get("host").toString();
		String url = api.get("url").toString();
		String email = api.get("email").toString();
		String param = api.get("param").toString();
		Map paramMap = JSONObject.parseObject(param, Map.class);
		String str = Main.api.getBase().post(host + url, paramMap);
		Map assertMap = JSONObject.parseObject(api.get("assert"), Map.class);
		Map monitor = JSONObject.parseObject(api.get("monitor"), Map.class);
		String rule = assertMap.get("rule").toString();
		String expect = assertMap.get("expect").toString();
		Object obj = scope.callMethod(scope, rule, new Object[] { str, expect });
		if (!obj.equals(true)) {

			email = (monitor.get("email") == null || monitor.get("email").equals("")) ? email : monitor.get("email").toString();

			PreparedStatement stmt = null;
			try {
				String sql = "INSERT INTO monitor ( host, url, param, result,create_time) VALUES ( ?, ?, ?, ?,? )";
				stmt = con.prepareStatement(sql);
				stmt.setString(1, host);
				stmt.setString(2, url);
				stmt.setString(3, param);
				stmt.setString(4, str);
				// stmt.setTime(5, new Time(new java.util.Date().getTime()));
				stmt.setObject(5, new java.util.Date(), Types.TIMESTAMP);
				stmt.execute();
				stmt.close();

				// String sql =
				// "INSERT INTO monitor ( host, url, param, result,create_time) VALUES ( '%s', '%s', '%s', '%s',%s )";
				// sql = String.format(sql, safeStr(host), safeStr(url),
				// safeStr(param), safeStr(str), new Date().getTime() / 1000);
				// stmt.execute("INSERT INTO monitor.monitor ( host, url, param, result) VALUES ( 'host', 'url', 'param', 'result')");
				// stmt.execute(sql);
			} catch (Exception e) {
				stmt = null;
				// e.printStackTrace();

			} finally {
				stmt = null;
			}

			boolean success = MailFactory.getInstance().send(email, email, "接口监控", url + param);
			if (success) {
				System.out.println("通知邮件已送到\t" + email);
			}
		}

	}
}